from flask import Flask,request,url_for,redirect,make_response,jsonify,session,abort
from jinja2.utils import generate_lorem_ipsum
import click
import os

app = Flask(__name__)

app.secret_key = os.getenv('SECRET_KEY','secdefault')

@app.route('/')
def index():
    name = request.args.get('name')
    resp = '<h1>Hello,%s!</h1>' % name
    if name is None:
        name = request.cookies.get('name','Human')
        resp = '<h1>Hello,%s!</h1>' % name
        if 'logged_in' in session:
            resp += '[Authenticated]'
        else:
            resp += '[Not Authenticated]'
    return resp

#多路由绑定，路由名字区分大小写
@app.route('/hello',methods=['GET','POST'])
@app.route('/sayHello')
def say_hello():
    return '<h1>Hello Flask!</h1>'

@app.route('/helloq')
def hello():
    #name = request.args['name']
    name = request.args.get('name','Human')
    return '<h1>Hello query %s</h1>' % name


#传递参数及缺省参数
@app.route('/gree',defaults={'name':'amy'})
@app.route('/gree/<name>')
def gree(name):
    return '<h1>Hello %s!</h1>' % name

@app.route('/goback/<int:year>')
def go_back(year):
    return '<p>Welcome to %d!</p>' % (2018-year)

@app.route('/hi')
def hi():
    return '',302,{'Location':'http://www.ifeng.com'}


@app.route('/redirect')
def helloredirect():
    return redirect(url_for('hello'))

@app.route('/foo')
@app.route('/foo/text')
def makeresponse():
    resp = make_response('<h1>Hello,World</h1>')
    resp.mimetype = 'text/plain'
    return resp

@app.route('/foo/html')
def makhtml():
    resp = make_response('<h1>Hello,World</h1>')
    resp.mimetype = 'text/html'
    return resp

@app.route('/foo/xml')
def makexml():
    resp = make_response('<h1>Hello,World</h1>')
    resp.mimetype = 'text/xml'
    return resp

@app.route('/foo/json')
def makejson():
    data = {
        'name':'Grey Li',
        'gender':'male'
    }
    return jsonify(data)

#模拟登录
@app.route('/login')
def login():
    session['logged_in'] = True
    return redirect(url_for('index'))

@app.route('/logout')
def logout():
    if 'logged_in' in session:
        session.pop('logged_in')
    return redirect(url_for('index'))


@app.route('/admin')
def admin123():
    if 'logged_in' not in session:
        abort(403)
    return 'Welcome to admin page.'


@app.route('/post')
def show_post():
    post_body = generate_lorem_ipsum(n=2)
    return """
        <!DOCTYPE html>
        <html lang="en">
            <head>
            <meta charset="UTF-8">
            <title>load More</title>
            </head>
            <body>
                <h1>A very long post</h1>
                <div class="body">%s</div>
                <button id="load">Load More</button>
                <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
                <script type="text/javascript">
                    $(function(){
                        $("#load").click(function(){
                            $.ajax({
                                url:'/more',
                                type:'get',
                                success:function(data){
                                    $(".body").append(data);
                                }
                            })
                        })
                    })
                </script>
            </body>
        </html>
    """ % post_body


@app.route('/more')
def load_post():
    return generate_lorem_ipsum(n=1)



@app.cli.command('hello')
def clihello():
    click.echo('Hello,Human!')




if __name__ == '__main__':
    app.run()
